import React, { useEffect, useState } from 'react';
import { Col, Icon, Row, Spin, Tooltip } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Charts, { Gauge } from './Charts';
import numeral from 'numeral';
import { IVisitData } from '../data.d';
import GaugeColor from './Charts/GaugeColor/index';
import apis from '@/services';
import moment from 'moment';
import { getWebsocket } from '@/layouts/GlobalWebSocket';
import styles from './introduceRow.less';




const { ChartCard, MiniArea, MiniBar, Field } = Charts;

interface State {
  cpu: number;
  memoryMax: number;
  memoryUsed: number;
  messageData: any[];
  sameDay: number;
  month: number;
  metadata: any;
  eventData: any[];
  leftVal: any[];
  rightVal: any[];
  proportion: any[];
}

const topColResponsiveProps = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 6,
  style: { marginBottom: 24 },
};

const IntroduceRow = ({ loading, visitData }: { loading: boolean; visitData: IVisitData[] }) => {
  const initState: State = {
    cpu: 0,
    memoryMax: 0,
    memoryUsed: 0,
    messageData: [],
    sameDay: 0,
    month: 0,
    metadata: {},
    eventData: [],
    rightVal: [{
      val: 0,
      name: ''
    }, {
      val: 0,
      name: ''
    }, {
      val: 0,
      name: ''
    }
    ],
    leftVal: [
      {
        val: 0,
        name: ""
      },
      {
        val: 0,
        name: ""
      },
      {
        val: 0,
        name: ""
      }
    ]
  };

  const [cpu, setCpu] = useState(initState.cpu);
  const [memoryMax, setMemoryMax] = useState(initState.memoryMax);
  const [memoryUsed, setMemoryUsed] = useState(initState.memoryUsed);
  const [sameDay, setSameDay] = useState(initState.sameDay);
  const [month, setMonth] = useState(initState.month);
  const [deviceOnline, setDeviceOnline] = useState(initState.month);
  const [deviceCount, setDeviceCount] = useState(initState.month);
  const [deviceNotActive, setDeviceNotActive] = useState(initState.month);
  const [messageData] = useState(initState.messageData);
  const [deviceCountSpinning, setDeviceCountSpinning] = useState(true);
  const [deviceMessageSpinning, setDeviceMessageSpinning] = useState(true);
  const [rightVal, setRightList] = useState(initState.rightVal);
  const [leftVal, setLeftList] = useState(initState.leftVal);



  const calculationDate = () => {
    const dd = new Date();
    dd.setDate(dd.getDate() - 30);
    const y = dd.getFullYear();
    const m = (dd.getMonth() + 1) < 10 ? `0${dd.getMonth() + 1}` : (dd.getMonth() + 1);
    const d = dd.getDate() < 10 ? `0${dd.getDate()}` : dd.getDate();
    return `${y}-${m}-${d} 00:00:00`;
  };

  const deviceMessage = () => {
    const list = [
      {
        'dashboard': 'device',
        'object': 'message',
        'measurement': 'quantity',
        'dimension': 'agg',
        'group': 'sameDay',
        'params': {
          'time': '1d',
          'format': 'yyyy-MM-dd',
        },
      },
      {
        'dashboard': 'device',
        'object': 'message',
        'measurement': 'quantity',
        'dimension': 'agg',
        'group': 'sameMonth',
        'params': {
          'limit': 30,
          'time': '1d',
          'format': 'yyyy-MM-dd',
          'from': calculationDate(),
          'to': moment(new Date()).add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00'
        },
      },
      {
        'dashboard': 'device',
        'object': 'message',
        'measurement': 'quantity',
        'dimension': 'agg',
        'group': 'month',
        'params': {
          'time': '1M',
          'format': 'yyyy-MM-dd',
          'from': calculationDate(),
          'to': moment(new Date()).add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00'
        },
      },
    ];
    apis.analysis.getMulti(list)
      .then((response: any) => {
        const tempResult = response?.result;
        if (response.status === 200) {
          tempResult.forEach((item: any) => {
            switch (item.group) {
              case 'sameDay':
                setSameDay(item.data.value);
                break;
              case 'month':
                setMonth(item.data.value);
                break;
              case 'sameMonth':
                messageData.push(
                  {
                    'x': moment(new Date(item.data.timeString)).format('YYYY-MM-DD'),
                    'y': Number(item.data.value),
                  });
                break;
              default:
                break;
            }
          });
        }
        setDeviceMessageSpinning(false);
      });
  };

  const deviceStatus = () => {
    const list = [
      // 设备状态信息-在线
      {
        'dashboard': 'device',
        'object': 'status',
        'measurement': 'record',
        'dimension': 'current',
        'group': 'deviceOnline',
        'params': {
          'state': 'online',
        },
      },// 设备状态信息-总数
      {
        'dashboard': 'device',
        'object': 'status',
        'measurement': 'record',
        'dimension': 'current',
        'group': 'deviceCount',
      },// 设备状态信息-未激活
      {
        'dashboard': 'device',
        'object': 'status',
        'measurement': 'record',
        'dimension': 'current',
        'group': 'deviceNotActive',
        'params': {
          'state': 'notActive',
        },
      },// 设备状态信息-历史在线
      {
        'dashboard': 'device',
        'object': 'status',
        'measurement': 'record',
        'dimension': 'aggOnline',
        'group': 'aggOnline',
        'params': {
          'limit': 20,
          'time': '1d',
          'format': 'yyyy-MM-dd',
        },
      },
    ];


    apis.analysis.searchCardRight()
      .then((response: any) => {
        const tempResult = response?.result;
        if (response.status === 200) {
          setRightList(tempResult)
        }
        setDeviceMessageSpinning(false);

      });

    apis.analysis.searchCardLeft()
      .then((response: any) => {
        const tempResult = response?.result;
        if (response.status === 200) {
          setLeftList(tempResult)
        }
        setDeviceMessageSpinning(false);
      });


  };

  useEffect(() => {
    deviceStatus();
    deviceMessage();

    let tempCup = getWebsocket(
      `home-page-statistics-cpu-realTime`,
      `/dashboard/systemMonitor/cpu/usage/realTime`,
      {
        params: {
          'history': 1,
        },
      },
    ).subscribe(
      (resp: any) => {
        const { payload } = resp;
        setCpu(payload.value);
      },
    );

    let tempJvm = getWebsocket(
      `home-page-statistics-jvm-realTime`,
      `/dashboard/jvmMonitor/memory/info/realTime`,
      {
        params: {
          'history': 1,
        },
      },
    ).subscribe(
      (resp: any) => {
        const { payload } = resp;
        setMemoryMax(payload.value.max);
        setMemoryUsed(payload.value.used);
      },
    );

    return () => {
      tempCup && tempCup.unsubscribe();
      tempJvm && tempJvm.unsubscribe();
    };
  }, []);

  return (
    <Row gutter={24}>

      <Col span={24}>
        <div className={styles.cardLeft}>
          <div className={styles.height}></div>
          <div className={styles.cardTitle}>
            {/* <strong className={styles.titleColor}>|</strong> */}
            <span className={styles.space}>统计</span>
          </div>
          <div className={styles.singleCard}>
            {/* 项目数量 */}
            <div className={styles.flex}>
              <div className={styles.firstData}>
                <div className={styles.tile}>{leftVal[0].name}</div>
                <div>
                  <span className={styles.font}>{leftVal[0].val}</span>
                  <span className={styles.littleFontSize}>个</span>
                </div>
              </div>
              <img src={require('./img/1-1.png')} alt="" />
            </div>
            {/* 设备种类 */}
            <div className={styles.flex}>
              <div className={styles.secondData}>
                <div className={styles.tile}>{leftVal[1].name}</div>
                <div>
                  <span className={styles.font}>{leftVal[1].val}</span>
                  <span className={styles.littleFontSize}>个</span>
                </div>
              </div>
              <img src={require('./img/1-2.png')} alt="" />
            </div>
            {/* 协议种类 */}
            <div className={styles.flex}>
              <div className={styles.thirdData}>
                <div className={styles.tile}>{leftVal[2].name}</div>
                <div>
                  <span className={styles.font}>{leftVal[2].val}</span>
                  <span className={styles.littleFontSize}>个</span>
                </div>
              </div>
              <img src={require('./img/1-3.png')} alt="" />
            </div>
          </div>
        </div>
      </Col>
      <Col span={24} className={styles.card}>
        <div className={styles.cardRight}>
          {/* 设备总数 */}
          <div className={styles.flex}>
            <div className={styles.firstData}>
              <div className={styles.tile}>{rightVal[0].name}</div>
              <div>
                <span className={styles.font}>{rightVal[0].val}</span>
                <span className={styles.littleFontSize}>个</span>
              </div>
            </div>
            <img src={require('./img/2-1.png')} alt="" />
          </div>
          {/* 变量点数 */}
          <div className={styles.flex}>
            <div className={styles.secondData}>
              <div className={styles.tile}>{rightVal[1].name}</div>
              <div>
                <span className={styles.font}>{rightVal[1].val}</span>
                <span className={styles.littleFontSize}>个</span>
              </div>
            </div>
            <img src={require('./img/2-2.png')} alt="" />
          </div>

          {/* 报警数 */}
          <div className={styles.flex}>
            <div className={styles.thirdData}>
              <div className={styles.tile}>{rightVal[2].name}</div>
              <div>
                <span className={styles.font}>{rightVal[2].val}</span>
                <span className={styles.littleFontSize}>个</span>
              </div>
            </div>
            <img src={require('./img/2-3.png')} alt="" />
          </div>
          {/* <div className={styles.fourthData}>
            <div className={styles.rightImgFirst}>
              <span className={styles.rightSizeFirst}>{rightVal[0].val}</span>
            </div>
            <span className={styles.littleFontSize}>{rightVal[0].name}</span>
          </div> */}
          {/* <div className={styles.fourthData}>
            <div className={styles.rightImgSecond}>
              <span className={styles.rightSizeSecond}>{rightVal[1].val}</span>
            </div>
            <span className={styles.littleFontSize}>{rightVal[1].name}</span>
          </div> */}
          {/* <div className={styles.fourthData}>
            <div className={styles.rightImgThird}>
              <span className={styles.rightSizeThird}>{rightVal[2].val}</span>
            </div>
            <span className={styles.littleFontSize}>{rightVal[2].name}</span>
          </div> */}
        </div>
      </Col>
    </Row >

  );
};

export default IntroduceRow;
